<template>
  <div class="ps_container" style="padding: 10px">
    <el-tabs v-model="activeName">
      <el-tab-pane label="修改用户密码" name="first">
        <el-form
          :rules="rules"
          :model="formData"
          label-width="100px"
          style="max-width: 460px"
          label-position="left"
          ref="fromEL"
        >
          <el-form-item prop="oldpass" label="旧密码：">
            <el-input type="password" v-model.trim="formData.oldpass" />
          </el-form-item>
          <el-form-item prop="newpass" label="新密码：">
            <el-input type="password" v-model.trim="formData.newpass" />
          </el-form-item>
          <el-form-item prop="repass" label="再次输入：">
            <el-input type="password" v-model.trim="formData.repass" />
          </el-form-item>
        </el-form>
        <el-row justify="space-evenly">
          <el-col :span="6">
            <el-button type="primary" @click="submit">确定</el-button>
          </el-col>

          <el-col :span="6">
            <el-button type="info" @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="修改用户名称" name="second">
        <el-form
          label-width="100px"
          :model="profile"
          :rules="profileRules"
          style="max-width: 460px"
          label-position="left"
          ref="nicknameEL"
        >
          <el-form-item prop="nickname" label="用户编号：">
            <el-input v-model.trim="profile.username" disabled />
          </el-form-item>
          <el-form-item prop="nickname" label="用户名称：">
            <el-input v-model.trim="profile.nickname" @keyup.enter="nickNameSubmit" />
          </el-form-item>
        </el-form>

        <el-row justify="space-evenly">
          <el-col :span="6">
            <el-button type="primary" @click="nickNameSubmit">确定</el-button>
          </el-col>

          <el-col :span="6">
            <el-button type="info" @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="修改头像" name="three">
        <ps-upload v-model="formData.avatar"></ps-upload>

        <el-row justify="space-evenly">
          <el-col :span="6">
            <el-button type="primary" @click="upload">确定</el-button>
          </el-col>

          <el-col :span="6">
            <el-button type="info" @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { verifyUserPass, reUserPass, updateNickname, updateAvatar } from '@/api/user.js'
import { required, length } from '@/utils/rules.js'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { userStore } from '@/pinia/user'

const UserStore = userStore()
const id = JSON.parse(localStorage.getItem('profile')).userID
const profile = ref(JSON.parse(localStorage.getItem('profile')))
const activeName = ref('first')
const router = useRouter()
const fromEL = ref()
const nicknameEL = ref()

const formData = ref({
  oldpass: '',
  newpass: '',
  repass: '',
  avatar: ''
})

const profileRules = {
  nickname: [required('昵称'), length(3, 8, '昵称')]
}

const rules = {
  oldpass: [
    required('旧密码'),
    length(6, 18, '旧密码'),
    {
      validator: async (rule, value, callback) => {
        const { data } = await verifyUserPass({ oldpass: value, id })
        return data ? callback() : callback(new Error('密码错误请重新输入'))
      },
      trigger: 'blur'
    }
  ],
  newpass: [required('新密码'), length(6, 18, '新密码')],
  repass: [
    required('新密码'),
    length(6, 18, '新密码'),
    {
      validator: async (rule, value, callback) => {
        return value === formData.value.newpass ? callback() : callback(new Error('两次密码不一致'))
      },
      trigger: 'blur'
    }
  ]
}

const submit = async () => {
  await fromEL.value.validate()

  try {
    const { message } = await reUserPass({ newPass: formData.value.repass, id })
    localStorage.removeItem('🎈token')
    localStorage.removeItem('menus')
    localStorage.removeItem('routes')
    localStorage.removeItem('profile')
    router.push('/login')
    ElMessage({ type: 'success', message })
  } catch (error) {
    ElMessage.error('错误')
  }
}
const upload = async () => {
  if (!formData.value.avatar) return ElMessage.error('请上传头像')
  await updateAvatar({ userID: profile.value.userID, avatar: formData.value.avatar })
  await UserStore.loadUserInfo()
  ElMessage.success('修改成功！')
}

const nickNameSubmit = async () => {
  await nicknameEL.value.validate()
  await updateNickname({ newNickname: profile.value.nickname, userId: id })
  await UserStore.loadUserInfo()
  ElMessage.success('修改成功！')
}

const reset = async () => {
  await fromEL.value.resetFields()
  profile.value = JSON.parse(localStorage.getItem('profile'))
  formData.value.avatar = profile.value.avatar
}
</script>

<style scoped lang="scss"></style>
